//
//  WorldViewController.m
//  markmap
//
//  Created by 甘世清 on 2024/3/24.
//

#import "WorldViewController.h"
#import <MapKit/MapKit.h>
#import "RankingViewController.h"
 
@interface WorldViewController ()<MKMapViewDelegate>
@property (nonatomic , strong) MKMapView * mapView;
@property (nonatomic , strong) UIButton * topBtn;
@property (nonatomic , strong) SQCustomButton * dingwei;

@end

@implementation WorldViewController
 
 
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.zx_navTitle = SQNSLocalString(@"全部");
    [self.zx_navRightBtn setTitleColor:UIColor.whiteColor forState:normal];
    [LocationPermissionView SQ_Show:self.view];
}
- (void)SQ_UIViewForSelfView{
    [self.view addSubview:self.mapView];
    CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake([UserModel share].lat, [UserModel share].lng);
       // 设置地图显示区域的缩放级别
       float zoomLevel = 0.005;
       // 初始化一个常量，表示地图对象的显示区域
       MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
       // 设置地图对象的显示区域
    [self.mapView setRegion:[self.mapView regionThatFits:region] animated:YES];
    [self.topBtn setTitle:self.topModel.topString forState:normal];
    [self.view addSubview:self.topBtn];
    [self.topBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.view);
            make.width.mas_equalTo(140);
            make.height.mas_equalTo(40);
            make.top.equalTo(self.zx_navBar.mas_bottom).offset(20);
    }];
    [self.view addSubview:self.dingwei];
    [self.dingwei mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(self.view.mas_bottom).offset(-FootHeight-100);
           make.size.mas_equalTo(50);
            make.left.equalTo(self.view.mas_left).offset(10);
    }];
    WS(weakSelf);
    [self.dingwei setTouchBlock:^(SQCustomButton * _Nonnull button) {
        [[SQCLLocationManager sharedManager] SQ_startUpdatingLocation];
        CLLocationCoordinate2D coordinate2D = CLLocationCoordinate2DMake([UserModel share].lat, [UserModel share].lng);
           float zoomLevel = 0.005;
           MKCoordinateRegion region = MKCoordinateRegionMake(coordinate2D, MKCoordinateSpanMake(zoomLevel, zoomLevel));
        [weakSelf.mapView setRegion:[weakSelf.mapView regionThatFits:region] animated:YES];
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self SQ_Header];
    });
}
- (void)SQ_Header{
  
    CLLocationCoordinate2D  location =  [self.mapView convertPoint:CGPointMake(SCREEN_WIDETH/2.f, SCREEN_HEIGHT/2.f) toCoordinateFromView:self.mapView];
    NSMutableDictionary * dic = [[NSMutableDictionary alloc]init];
    if (self.topModel.type ==0 ||self.topModel.type==1 ) {
        [dic setObject:[NSString stringWithFormat:@"%.7f",location.latitude] forKey:@"lat"];
        [dic setObject:[NSString stringWithFormat:@"%.7f",location.longitude] forKey:@"lng"];
    }else {
        [dic setObject:@(self.page) forKey:@"current"];
        [dic setObject:@"20" forKey:@"size"];
    }
    
    [HttpTool post:self.topModel.url paramDic:dic successBlock:^(BaseModel * _Nonnull httpModel) {
        self.page++;
        if (self.page >5) {
            self.page = 1;
        }
        NSArray * array = [HomeTopModel SQ_GetArray:httpModel type:self.topModel.type];
        if (array.count <=0) {
            [YJProgressHUD showMsgWithoutView:self.topModel.messageString];
            return;
        }
        [self.jsonArray removeAllObjects];
        for (PointModel * mo in array) {
            BaseAnntation *pointAnnotation = [[BaseAnntation alloc] init];
            pointAnnotation.coordinate = CLLocationCoordinate2DMake(mo.lat, mo.lng);
            pointAnnotation.model = mo;
            [self.jsonArray addObject:pointAnnotation];
        }
        [self.mapView removeAnnotations:self.mapView.annotations];
        [self.mapView addAnnotations:self.jsonArray];
        [self.mapView showAnnotations:self.jsonArray animated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.topBtn.hidden = YES;
        });
    } andFailBloc:^(BaseModel * _Nonnull httpModel, NSError * _Nullable error) {
        [YJProgressHUD showMsgWithoutView:httpModel.message];
    }];
}
//位置已经改变了
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    self.topBtn.hidden = NO;
        [self.mapView removeFromSuperview];
        [self.view addSubview:mapView];
        [self.view sendSubviewToBack:mapView];
}
//设置大头针
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
    
    if (![annotation isKindOfClass:[BaseAnntation class]]) {// 过滤掉MKUserLocation
        return nil;
    }
   
    BaseAnntation* ann = (BaseAnntation *)annotation;
    BaseAnnotationView *annotationView = (BaseAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:ann.model.annotationViewIdentifier];
    if (!annotationView) {
       annotationView = [[BaseAnnotationView alloc] initWithAnnotation:ann
                                                     reuseIdentifier:ann.model.annotationViewIdentifier];
        annotationView.opaque = NO;
    }
    annotationView.model = ann.model;
    annotationView.show = self.topModel.show;
    return annotationView;
}
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view{
   
}



- (void)dealloc {
    _mapView.showsUserLocation = NO;
    _mapView.userTrackingMode  = MKUserTrackingModeNone;
    [_mapView.layer removeAllAnimations];
    [_mapView removeAnnotations:_mapView.annotations];
    [_mapView removeOverlays:_mapView.overlays];
    [_mapView removeFromSuperview];
    _mapView.delegate = nil;
    _mapView = nil;
}


/** 懒加载地图视图 */
- (MKMapView *)mapView{
    if (!_mapView) {
        _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDETH, SCREEN_HEIGHT)];
        /** 设置地图类型 */
        _mapView.mapType = MKMapTypeMutedStandard;
        _mapView.userTrackingMode = MKUserTrackingModeFollow;
        //设置地图可缩放
        _mapView.zoomEnabled = YES;
        //设置地图可滚动
        _mapView.scrollEnabled = YES;
        //设置地图可旋转
        _mapView.rotateEnabled = YES;
        //设置显示用户显示位置
//        _mapView.showsUserLocation = YES;
        //为MKMapView设置delegate
        _mapView.delegate = self;
//        _mapView.showsBuildings = YES;
//        _mapView.showsTraffic = YES;
    }
    return _mapView;
}

- (UIButton *)topBtn{
    if (!_topBtn) {
        _topBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _topBtn.backgroundColor = UIColor.whiteColor;
        _topBtn.layer.cornerRadius = 6;
        _topBtn.layer.masksToBounds = YES;
        _topBtn.titleLabel.font = FONT_MEDIUM(14);
        [_topBtn setTitleColor:SQColor333333 forState:normal];
        _topBtn.hidden = YES;
        [_topBtn addTarget:self action:@selector(SQ_Header) forControlEvents:UIControlEventTouchUpInside];
    }
    return _topBtn;
}
- (SQCustomButton *)dingwei{
    if (!_dingwei) {
        _dingwei = [[SQCustomButton alloc]initType:SQCustomButtonTopImageType imageSize:CGSizeMake(30, 30) midmargin:0];
        _dingwei.image = SQGetImage(@"zishendingwei");
    }
    return _dingwei;
}
@end
